<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/22 0022
 * Time: 下午 2:58
 */

namespace app\admin\controller;


use app\admin\model\UserModel;
use app\admin\validate\UserValidate;
use think\captcha\Captcha;
use think\Controller;
use think\facade\Cookie;
use think\facade\Session;
use think\Request;

class Login extends Controller
{

    protected $time = 10;

    public function login()
    {
        $redis = new \Redis();
        $redis->connect("127.0.0.1",6379);
        $loginError = $redis->get("loginError");
        if ($loginError === false) {
            $loginError = 0;
        }
        $this->assign("loginError",$loginError);
        return $this->fetch();
    }

    /**
     * 用户登入
     * @param Request $request
     * @return \think\response\Json
     */
    public function userLogin(Request $request)
    {

        $redis = new \Redis();
        $redis->connect("127.0.0.1",6379);
        //获取错误次数
        $loginError = $redis->get("loginError");
        if ($loginError === false) $redis->set("loginError",0);
        //如果错误五次
        if ($loginError == 5) {
            $redis->incr("loginError"); //增加一次
            $redis->set("errorTime" . $request->ip(),time() + $this->time,$this->time); //存储当前时间加上60  并且到点失效
            $redis->set("errorStatus" . $request->ip(),"true",$this->time);  //1分钟失效
        }

        $errorStatus = $redis->get("errorStatus" . $request->ip()); //获取 并判断是否为true
        if ($errorStatus == true) {
            $errorTime = $redis->get("errorTime" . $request->ip()); //获取 存储时间 减去当前时间 提示 前端
            return json([
                "code" => 404,
                "msg" => "访问失败",
                "data" => "由于您失败次数超过五次，请您等待{$this->time}秒！！！\n 您还需等待:" . ($errorTime - time() . "秒")
            ]);
        }

        if ($request->isPost() && $request->isAjax()) {

            $data = $request->post();

            //验证
            $validate = new UserValidate();

            $validate = $loginError >= 3 ? $validate->scene("code") : $validate->scene("login");

            if (!$validate->check($data)) {
                //自增
                $redis->incr("loginError");
                //获取判断 反馈前端
                $loginError = $redis->get("loginError");
                return json([
                    "code" => 403,
                    "msg" => "失败" ,
                    "data" => $validate->getError(),
                    "token" => $request->token(),
                    "error" => $loginError >= 3 ? true : false,
                    "captcha" => captcha_src()
                ]);

            }
            //获取验证数据
            $userData = $validate->userData;

            //增加 登入时间  IP地址
            UserModel::recordIp($userData["id"]);
            //清空错误次数
            $redis->set("loginError",0,1);
            //记录数据登入者数据
            Session::set("userData",$userData);
            Cookie::set("userId",$userData["id"]);
            $result = (new UserModel())->get($userData["id"])->role()->field("name")->find();
            //登入成功
            return json([
                "code" => 1,
                "msg" => "登入成功",
                "data" => "欢迎 " . " {$result["name"]} \n {$userData['username']}"
            ]);
        } else {
            return $this->fetch('index/403');
        };
    }

    /**
     * 退出登入
     */
    public function outLogin()
    {
        Session::delete("userData");
        Cookie::delete("userId");
        $this->success("退出成功",url('/admin/login/login'),"",1);
    }
}